/**
 * 获取本地缓存的IP地址
 * @returns {string} IP地址
 */
export function getIp() {
  return localStorage.getItem('userIP') || '';
}

/**
 * 设置IP地址到本地缓存
 * @param {string} ip IP地址
 */
export function setIp(ip) {
  if (ip && typeof ip === 'string' && ip.trim()) {
    localStorage.setItem('userIP', ip.trim());
  }
}

/**
 * 获取当前用户IP地址
 * 使用多个API服务，优先使用适合中国地区的服务
 * @returns {Promise<string>} IP地址
 */
export async function getCurrentUserIP() {
  // 定义多个IP获取服务，按优先级排序（适合中国地区的在前）
  const ipServices = [
    // 中国地区友好的IP服务
    {
      url: 'https://myip.ipip.net/json',
      parser: (data) => data.data?.ip,
      timeout: 3000
    },
    {
      url: 'https://httpbin.org/ip',
      parser: (data) => data.origin,
      timeout: 3000
    },
    {
      url: 'https://api.ip.sb/ip',
      parser: (data) => typeof data === 'string' ? data.trim() : data,
      timeout: 3000
    },
    
    // 备用服务
    {
      url: 'https://api.ipify.org?format=json',
      parser: (data) => data.ip,
      timeout: 3000
    },
    {
      url: 'https://jsonip.com',
      parser: (data) => data.ip,
      timeout: 3000
    }
  ];

  // 尝试每个服务，直到成功获取IP
  for (const service of ipServices) {
    try {
      // 创建一个带超时的fetch请求
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), service.timeout);

      const response = await fetch(service.url, {
        signal: controller.signal,
        headers: {
          'Accept': 'application/json',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        continue;
      }

      // 根据响应类型解析数据
      let data;
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        data = await response.json();
      } else {
        data = await response.text();
      }

      const ip = service.parser(data);

      if (ip && typeof ip === 'string' && ip.trim()) {
        // 简单的IP地址格式验证
        const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        const cleanIp = ip.trim();

        if (ipRegex.test(cleanIp)) {
          console.log(`成功从 ${service.url} 获取IP: ${cleanIp}`);
          // 自动保存到本地缓存
          setIp(cleanIp);
          return cleanIp;
        }
      }
    } catch (error) {
      console.warn(`从 ${service.url} 获取IP失败:`, error.message);
      continue;
    }
  }

  // 如果所有服务都失败，返回空字符串
  console.warn('所有IP获取服务都失败，返回空字符串');
  return '';
}